//
//  PurchasesFirstViewController.m
//  Consume100
//
//  Created by eliot on 16/3/24.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "PurchasesFirstViewController.h"
#import "GoodsFirstTableViewCell.h"
#import "MJRefresh.h"
#import "PurchasesTableViewCell.h"
#import "RechargeViewController.h"
#import "luckilyPersonTableViewController.h"
#import "JoinINMainViewController.h"
#import "UIImageView+WebCache.h"
//#import "JoinInPurchasesTableViewController.h"
@interface PurchasesFirstViewController ()<UITableViewDataSource, UITableViewDelegate>


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewTop;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic ,strong) NSTimer *timer;

/** 滚动页点*/
@property (nonatomic ,strong) UIPageControl *page;
/** 滚动视图*/
@property (nonatomic, strong) UIScrollView *sc;
/** 滚动图片数组*/
@property (nonatomic, strong) NSMutableArray *imageArray;

/** 数据源*/
@property (nonatomic, strong) NSMutableDictionary *dataDic;

/** 幸运用户  数据*/
@property (nonatomic, strong) NSArray *luckPersonArr;

/** 众筹中  数据*/
@property (nonatomic, strong) NSMutableArray *crowdingArr;



@end

@implementation PurchasesFirstViewController

static int pindex = 1;


-(NSMutableArray *)crowdingArr {
    if (!_crowdingArr) {
        _crowdingArr = [NSMutableArray array];
    }
    return _crowdingArr;
}


- (NSMutableDictionary *)dataDic {
    if (!_dataDic) {
        _dataDic = [NSMutableDictionary dictionary];
    }
    return _dataDic;
}


-(NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}


- (UIScrollView *)sc {
    if (!_sc) {
        _sc = [[UIScrollView alloc] init];
    }
    return _sc;
}

-(UIPageControl *)page {
    if (!_page) {
        _page = [[UIPageControl alloc] init];
        [self.tableView addSubview:_page];
        [_page mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(self.view.frame.size.width);
            make.top.mas_equalTo(self.sc.frame.size.height - 20);
            make.height.mas_equalTo(20);
        }];
        [_page setAlpha:1];
    }
    return _page;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        [self setMyScrollView];
        return self.sc;
    }else {
        
        return nil;
    }
}


/** 设置滚动视图*/
- (void)setMyScrollView {
    self.sc.showsHorizontalScrollIndicator = NO;
    self.sc.frame = CGRectMake(0, 0, Width, 158/320.0*Width);
    //创建页点
   // UIPageControl *tempPage = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 222/320.0*Width - 20, Width,20)];
    
   // [tempPage setBackgroundColor:[UIColor redColor]];
   // [tempPage setAlpha:1];
   // self.page = tempPage;
    
    //[self.sc addSubview:self.page];
    
    [self createsCrollView:nil];
}


#pragma ------创建视图区域----------
//创建滚动视图区域
- (void)createsCrollView:(id)sender {
    //设置委托
    self.sc.delegate = self;
    //将是否取消对内容视图触摸的反应设为NO
    self.sc.canCancelContentTouches = NO;
    //设置滚动条类型
    // self.scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    //是否可以缩放
    self.sc.scrollEnabled = YES;
    //是否可以进行页面切换
    self.sc.pagingEnabled = YES;
    NSUInteger page = 0;//为了记录页数
    int originX = 0;
    //填充滑动视图内容
    for (NSDictionary *imageDic in self.imageArray) {
        
        //首先创建一个视图
        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectZero];
        imageview.contentMode = UIViewContentModeScaleToFill;
        //为这个图片设置适当位置
        CGRect rect ;
        rect.origin.x = originX;
        rect.origin.y = 0;
        rect.size.width = Width;
        rect.size.height = 158/320.0*Width;
        imageview.frame = rect;
        //设置图片为背景
        [imageview sd_setImageWithURL:[NSURL URLWithString:imageDic[@"img"]]];
        //添加到视图中
        [self.sc addSubview:imageview];
        //确定下张图片开始的x坐标
        originX += Width;
        //记录页数
        page++;
    }
    //设置总页数
    self.page.numberOfPages = page;
    //设置默认页为首页
    self.page.currentPage = 0;
    self.page.tag = 100;
    //为页数控制关联方法
    [self.page addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    //显示适当区域
    [self.sc setContentSize:CGSizeMake(originX, 158/320.0*Width)];
}
- (void)repartScroll {
    if (self.page.currentPage == self.imageArray.count - 1) {
        self.page.currentPage = 0;
        [self.sc setContentOffset:CGPointMake(0, 0) animated:NO];
        
    }else{
        self.page.currentPage = self.page.currentPage + 1;
    }
    CGRect rect;
    rect.origin.x = self.page.currentPage * self.sc.frame.size.width;
    rect.origin.y = 0;
    rect.size.width = Width;
    rect.size.height = 222/320.0*Width;
    //设置滚动视图的可视区域
    [self.sc scrollRectToVisible:rect animated:YES];
    
}

//点击小点切换页面
- (void)changePage:(id)sender {
    //创建一个区域
    CGRect rect;
    rect.origin.x = self.page.currentPage * self.sc.frame.size.width;
    rect.origin.y = 0;
    rect.size.width = self.sc.frame.size.width;
    rect.size.height = self.sc.frame.size.height;
    //设置滚动视图的可视区域
    [self.sc scrollRectToVisible:rect animated:YES];
    
}

//重写滑动结束后的反应，就是把pageConteol的当前页跟随滑动而动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //取滚动视图区域的宽
    float orginX = self.sc.frame.size.width;
    //利用当前视图显示区域到view.frame的偏移量，来换算获取当前处在第几页
    int page = ((self.sc.contentOffset.x - orginX))/orginX +1;
    //当前页改为这一页。
    self.page.currentPage = page;
}



//页面将要进入前台，开启定时器
-(void)viewWillAppear:(BOOL)animated
{
    //开启定时器
    [self.timer setFireDate:[NSDate distantPast]];
}

//页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
    //关闭定时器
    [self.timer setFireDate:[NSDate distantFuture]];
}

/** 加载更多数据*/
- (void)loadMoreData {
    pindex += 1;
    UserModel *moedl = userModel;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d", pindex],@"consumerId":moedl.id};
    NSString *baseUrl = [NSString stringWithFormat:@"%@crowdfundingIndex.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dddic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.mj_footer endRefreshing];
            
            [self.crowdingArr addObjectsFromArray:dddic[@"pageCrowdfundingList"]];
            
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"PurchasesTableViewCell" bundle:nil] forCellReuseIdentifier:@"PurchasesTableViewCell"];
    MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer = footer;
    self.view.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    self.tableView.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
    /** 设置导航啦样式*/
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.75 target:self selector:@selector(repartScroll) userInfo:nil  repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

    UserModel *moedl = userModel;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"page":@"1",@"consumerId":moedl.id};
    NSString *baseUrl = [NSString stringWithFormat:@"%@crowdfundingIndex.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dddic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dataDic = [NSMutableDictionary dictionaryWithDictionary:dddic];
            self.crowdingArr = [NSMutableArray arrayWithArray:dddic[@"pageCrowdfundingList"]];
            self.imageArray = dddic[@"bannersList"];
            
        
            
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4 + self.crowdingArr.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 0;
            break;
        case 1:
            return 1;
            break;
        case 2:
        {
            NSArray *tempArr = self.dataDic[@"crowdfundingList"];
        
            if (tempArr.count >3) {
                return 4;
            }else {
                return tempArr.count + 1;
            }
        }
            break;
        default:
            return 1;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    tableView.showsVerticalScrollIndicator = NO;
    if (indexPath.section == 0) {
        return nil;
    }else if (indexPath.section == 1){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        cell.textLabel.textColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1];
        cell.imageView.image = [UIImage imageNamed:@"icon_myGold"];
        NSString *str = [NSString stringWithFormat:@"我的金币 %@", self.dataDic[@"consumerCoins"][0]];
        str = [str stringByReplacingOccurrencesOfString:@")" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"(" withString:@""];
        cell.textLabel.text = str;
        UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [cell addSubview:btn1];
        [btn1 setTitle:@"充值金币" forState:UIControlStateNormal];
        [btn1 addTarget:self action:@selector(clickRechargeBtn) forControlEvents:UIControlEventTouchUpInside];
        btn1.layer.cornerRadius = 4;
        btn1.layer.masksToBounds = YES;
        btn1.backgroundColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
        [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-10);
            make.size.mas_equalTo(CGSizeMake(80, 30));
            make.top.mas_equalTo(10);
        }];
        return cell;
    }else if(indexPath.section == 2) {
        if (indexPath.row == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
            }
            UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_luckymen"]];
            imageView.contentMode = UIViewContentModeScaleAspectFit;
            [cell addSubview:imageView];
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(14);
                make.top.mas_equalTo(17);
                make.size.mas_equalTo(CGSizeMake(16, 16));
            }];
            
            UILabel *la = [[UILabel alloc] init];
            [cell addSubview:la];
            la.text = @"幸运用户";
            la.textColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1];
            [la mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(50);
                make.top.bottom.mas_equalTo(0);
                make.width.mas_equalTo(100);
            }];
            UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_arrows"]];
            iv.frame = CGRectMake(0, 0, 12, 12);
            iv.contentMode = UIViewContentModeScaleAspectFit;
            cell.accessoryView = iv;
            cell.detailTextLabel.text = @"查看更多";
            cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
            UIButton *btn = [[UIButton alloc] init];
            [cell addSubview:btn];
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.top.bottom.mas_equalTo(0);
                make.width.mas_equalTo(120);
            }];
            [btn addTarget:self action:@selector(clickSeeMoreBtn) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"crowdfundingList"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"crowdfundingList"];
            }
            UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_arrows"]];
            iv.frame = CGRectMake(0, 0, 12, 12);
            iv.contentMode = UIViewContentModeScaleAspectFit;
            cell.accessoryView = iv;
            NSArray *tempArr = self.dataDic[@"crowdfundingList"];
            NSArray *indexArr = tempArr[indexPath.row - 1];
            cell.textLabel.textColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1];
            cell.textLabel.text = indexArr[1];
            cell.detailTextLabel.text = indexArr[2];
            cell.detailTextLabel.textColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1];
            return cell;
        }
    }else if(indexPath.section == 3) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        }
        cell.imageView.image = [UIImage imageNamed:@"icon_time"];
        cell.textLabel.text = @"众筹中";
        cell.textLabel.textColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1];
        return cell;
    }else {
        PurchasesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PurchasesTableViewCell" forIndexPath:indexPath];
        cell.progressViewH.constant = 4;
        
        NSDictionary *tempDic = self.crowdingArr[indexPath.section - 4];
        
        [cell.iconIV sd_setImageWithURL:[NSURL URLWithString:tempDic[@"img"]]];
        cell.titleLb.text = tempDic[@"name"];
        
        cell.priceLb.text = [NSString stringWithFormat:@"￥%@", tempDic[@"price"]];
        
        cell.joinedLb.text = [NSString stringWithFormat:@"%d", [tempDic[@"countNum"] intValue]];
        
        cell.allNeedLb.text = [NSString stringWithFormat:@"%d", [tempDic[@"inNum"] intValue]];
        
        cell.toJoinLb.text = [NSString stringWithFormat:@"%d", [tempDic[@"inNum"] intValue] - [tempDic[@"countNum"] intValue]];
        
        cell.progressView.progress = [tempDic[@"countNum"] floatValue] / [tempDic[@"inNum"] floatValue];
        
       
        
        return cell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0) {
        return 0;
    }else if (indexPath.section == 1){
        return 50;
    }else if (indexPath.section == 2) {
        return 50;
    }else if (indexPath.section == 3) {
        return 50;
    }else {
        return 160;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section > 3) {
        JoinINMainViewController *vc = [JoinINMainViewController CreatJoinINMainViewController];
        
        NSDictionary *tempDic = self.crowdingArr[indexPath.section - 4];
        vc.crowdfundingId = tempDic[@"id"];
        
        [self creatNav:vc];
    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 158/320.0*Width;
    }else if (section == 1){
        return 0;
    }else if (section == 3){
        return 4;
    }else {
        return 10;
    }
}


/** 点击查看更多*/
- (void)clickSeeMoreBtn {
    luckilyPersonTableViewController *vc = [luckilyPersonTableViewController CreatluckilyPersonTableViewController];
    [self creatNav:vc];
}

/** 点击充值金币*/
- (void)clickRechargeBtn {
    RechargeViewController *vc = [RechargeViewController CreatRechargeViewController];
    
    [self creatNav:vc];
}


//创建模态导航控制器
-(void)creatNav:(UIViewController *)view{
    
    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:view];
    nav.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    view.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_back"] style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    [self.navigationController pushViewController:view animated:YES];
    self.tabBarController.tabBar.hidden = YES;
}




- (void)dismiss {
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
